package com.study.io.nio.demo.buffer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * HeapByteBuffer demo
 * 堆内存缓冲
 *
 * @author Lenovo
 */
public class HeapByteBufferDemo {

    public static void main(String[] args) {
        //写文件 通过Channel
        try {
            File file = new File("d://321.txt");
            FileOutputStream fos = new FileOutputStream(file);
            FileChannel fc = fos.getChannel();
            ByteBuffer heapByteBuffer = ByteBuffer.allocate(6).put("你好".getBytes());
            heapByteBuffer.flip();
            fc.write(heapByteBuffer);

            heapByteBuffer.clear();
            fos.flush();
            fos.close();
            fc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //读文件 通过Channel
        try {
            File file = new File("d://321.txt");
            FileInputStream fis = new FileInputStream(file);
            FileChannel fc = fis.getChannel();
            ByteBuffer heapByteBuffer = ByteBuffer.allocate(6);
            fc.read(heapByteBuffer);
            byte[] b = heapByteBuffer.array();
            System.out.println(new String(b));

            heapByteBuffer.clear();
            fis.close();
            fc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
